package pers.vic.blog.module.front.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.util.WebUtils;
import pers.vic.blog.module.front.model.RightAsideModel;
import pers.vic.blog.module.front.service.BlogHomeService;
import pers.vic.boot.base.web.intercept.SaveRequestInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Vic.xu
 * @description:
 * @date: 2020/7/10 0010 13:30
 */
public abstract  class BaseFrontController {

    protected static final String PAGER = "pager";

    protected static final String LOOKUP = "lookup";

    @Autowired
    private BlogHomeService blogHomeService;

    /**
     * 保存在session中的右侧的数据
     */
    protected static final String RIGHT_MODEL_SESSION = "RIGHT_MODEL_SESSION";

    /**
     * 保存在session中的用户信息(第三方登录用户)
     */
    protected static final String PRINCIPAL_SESSION = "principal";

    @Autowired
    protected HttpServletRequest rquest;

    @Autowired
    protected HttpServletResponse response;

    protected  <T> T getSessionAttribute(String key){
        return (T) WebUtils.getSessionAttribute(rquest, key);
    }

    protected  void setSessionAttribute(String key, Object object){
        WebUtils.setSessionAttribute(rquest, key, object);
    }

    /**
     * 返回通用的右侧数据
     */
    @ModelAttribute(name = "right")
    public RightAsideModel right(){
        RightAsideModel rightAsideModel = getSessionAttribute(RIGHT_MODEL_SESSION);
        if (rightAsideModel == null) {
            rightAsideModel = blogHomeService.queryRight();
            setSessionAttribute(RIGHT_MODEL_SESSION, rightAsideModel);
        }
        return rightAsideModel;
    }

    /**
     * 获取最后一次请求的url
     * @return
     */
    protected String lastUrl(){
        String url = getSessionAttribute(SaveRequestInterceptor.LAST_URL);
        return StringUtils.isEmpty(url) ? "/" : url;
    }

}
